<?php
/**
 * 根据时间取价格
 * Enter description here ...
 * @author nijn
 *
 */
class TimePriceBehavior extends CActiveRecordBehavior {

	/**
	 * 搜索价格模型（模型名称）
	 * Enter description here ...
	 * @var unknown_type
	 */
	public $findPriceModel = 'VGoodsPrice';
	
	public function timePriceObjAttr($attribute = 'price_refer', $time = '') {
		$owner = $this->owner;
		$attribute = empty($attribute) ? 'price_refer' : $attribute;
		$time = empty($time) ? date('Y-m-d') : $time;
		
		$criteria = new CDbCriteria();
		$criteria->compare('goods_id', $owner->primaryKey);
		$criteria->compare('datetime',$time,true);
		$model = new $this->findPriceModel;
		$obj = $model->find($criteria);
		if (!is_object($obj)) {
			$obj = $model->findByAttributes(array(
				'goods_id' => $owner->primaryKey,
				'is_default' => '1'
			));
		}
		return $obj->$attribute;
	}
	
	public function minPrice($time, $attribute = 'price_refer') {
		
		$owner = $this->owner;
		$model = new $this->findPriceModel;
		
		$criteria = new CDbCriteria();
		$criteria->select = "min($attribute) as {$attribute}";
		$criteria->join = "left join {$owner->tableName()} as r on t.goods_id = r.id";
		$criteria->compare('datetime', $time, true);
		
		$obj = $model->find($criteria);
		return !empty($obj->$attribute) ? $obj->$attribute : 0;
	}
	
}

?>